package cn.wolfcode.shop.web.controller;

import cn.wolfcode.shop.anno.UserParam;
import cn.wolfcode.shop.common.BusinessException;
import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.msg.SeckillServerCodeMsg;
import cn.wolfcode.shop.util.RedisKeys;
import cn.wolfcode.shop.util.VerifyCodeImgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 *  接口限流之验证码表达式
 */
@RestController
@RequestMapping("/api/verifyCode")
public class VerifyCodeController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping
    public void getVerifyCodeImg(@UserParam User user, Long seckillId, HttpServletResponse response)
            throws IOException {
        if (user == null) {
            throw new BusinessException(SeckillServerCodeMsg.NOTLOGIN_ERROR);
        }

        // 1. 调用工具类得到验证码表达式
        String verifyCode = VerifyCodeImgUtil.generateVerifyCode();
        // 2. 调用工具类根据表达式得到对应的验证码结果
        Integer ret = VerifyCodeImgUtil.calc(verifyCode);
        // 3. 将验证码表达式结果保存进Redis中
        redisTemplate.opsForValue().set(
                RedisKeys.SECKILL_VIREFY_CODE.join(user.getId() + "", seckillId + ""),
                ret + "",
                RedisKeys.SECKILL_VIREFY_CODE.getTime(),
                TimeUnit.SECONDS);
        // 4. 根据验证码表达式生成验证码图片
        BufferedImage verifyCodeImg = VerifyCodeImgUtil.createVerifyCodeImg(verifyCode);
        // 5. 将生成的图片响应给前端用户
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(verifyCodeImg, "JPEG", out);
    }
}
